package org.xilin.dev

import org.xilin.*

class SetupService {
    def authenticateService

    boolean transactional = true

    def setupDevData() {
        org.xilin.Book book
        org.xilin.Course course
        org.xilin.User user
        org.xilin.RoomSchedule roomSchedule
        //        def book, course, user, roomSchedule

        def defaultRole = new org.xilin.Role(authority: "ROLE_USER", description: "user family")
        defaultRole.save()
        user = createUser(defaultRole, "xilin", "xilin")
        def family = createFamily(user.username)
        createStudent(family)

        //def defaultRole = new org.xilin.Role(authority: "ROLE_USER", description: "teacher family")
        //defaultRole.save()
        //def aUser = createUser(defaultRole, "xilin10", "xilin10")
        //def family = createFamily(aUser.username)
        def admin = createAdmin()

        def teacherRole = new org.xilin.Role(authority: "ROLE_TEACHER", description: "teacher family")
        teacherRole.save(flush:true)

        def semesterStartDate = new Date().parse("MM/dd/yyyy H:m:s","09/01/2010 0:0:0");
        def semesterEndDate = new Date().parse("MM/dd/yyyy H:m:s","12/15/2010 0:0:0");
        def semester = createSemester('Fall', 2010, 'Y', semesterStartDate, semesterEndDate, admin)
        createSemester('Winter', 2010, 'Y', new Date('12/16/2010'), new Date('04/30/2011'), admin)
        
        (100g..130g).each {
            book = createBook("Math $it", semester)
            course = createCourse(book, semester, it)
            user = createUserTeacher(teacherRole, "teacher" + it, "teacher" + it)
            addTeacher('firstName', 'lastName', user, course)
            roomSchedule = createRoomSchedule(it, course)
        }
        
    }

    private def createSemester(term, year, active, startDate, endDate, updatedBy) {
        def semester = new org.xilin.Semester(semester:term,year:year, active:active,startDate:startDate, endDate:endDate, updatedBy:updatedBy)
        if (!semester.save(flush:true)) {
            println "ERROR"
            semester.errors.allErrors.each {
                println it
            }
        }
        return semester
    }

    private def createRoomSchedule(roomNumber, course) {
        def i = roomNumber
        def rn = roomNumber as String
        def startTime = 1200 + 100 * i
        def endTime = startTime + 100
        try
        {
            def roomS = new RoomSchedule()
            roomS.room = rn
            roomS.save(flush:true)

            if (roomS.hasErrors()) {
                println "errors=" + roomS.errors
            }
            return roomS
        }
        catch (Exception e) {
            println e.getMessage()

        }
        return null
    }
    
    private def createUserTeacher(defaultRole, username, password) {
        def passwd1 = authenticateService.passwordEncoder(password)
        def teacher = new org.xilin.User(username:username,passwd:passwd1,enabled:true,emailShow:true,description:"teacher",email:"xilin.it@gmail.com")
        if (!teacher.validate()) {
            println "Show error"
            teacher.errors.allErrors.each {
                println it
            }
        }
        if (!teacher.save(flush:true)) {
            println "Show error"
            teacher.errors.allErrors.each {
                println it
            }
        }
        teacher.refresh()

        defaultRole.addToPeople(teacher)
        defaultRole.save(flush:true)
        return teacher
    }

    private def createBook(bookName, semester) {

        try {
            return new Book(stock:10,price:30,description:bookName, name:bookName,reserve:0,semester:semester).save(flush:true)
        }
        catch (ex) {
            log.debug(ex.getMessage())
        }

        return null
    }

    private def createCourse(book, semester, number) {
        def i = number.remainder(5g)
        def startTimes = [0g:"13:00", 1g:"14:00", 2g:"15:00", 3g:"16:00", 4g:"13:00"]
        def endTimes = [0g:"13:50", 1g:"14:50", 2g:"15:50", 3g:"16:50", 4g:"14:50"]
        if(i==2g) {
            def params = [
                name        : book.name,            
                capacity    : 20,
                regCapacity : 18,
                price       : 20,
                semester    : semester,
                startTime   : startTimes.getAt(i),
                endTime     : endTimes.getAt(i)
            ]

            try {
                return new org.xilin.Course(params).save(flush:true);
            }
            catch (ex) {
                log.debug(ex.getMessage())
            }
        } else {
            def params = [
                name        : book.name,
                book        : book,
                capacity    : 20,
                regCapacity : 18,
                price       : 20,
                extraFee    : 1,    
                semester    : semester,
                startTime   : startTimes.getAt(i),
                endTime     : endTimes.getAt(i)
            ]

            try {
                return new org.xilin.Course(params).save(flush:true);
            }
            catch (ex) {
                log.debug(ex.getMessage())
            }
        }

        return null
    }

    private def addTeacher(firstName, lastName, user, course) {

        try {
            return new Teacher(firstName:firstName, lastName:lastName, user:user, type:'math', course:course).save(flush:true)
        }
        catch (ex) {
            log.debug(ex.getMessage())
        }

        return null
    }

    private def createUser(defaultRole, username, password) {

        def passwd1 = authenticateService.passwordEncoder(password)
        def user1 = new org.xilin.User(username:username,passwd:passwd1,enabled:true,emailShow:true,description:"user",email:"xilin.it@gmail.com")
        user1.save()
        defaultRole.addToPeople(user1)
        return user1
    }

    private def createFamily(username) {
        return new Family(userId:username,fatherFirstName:"y",fatherLastName:"Wang",motherFirstName:"Y",
            motherLastName:"Li",fatherChineseName:"",motherChineseName:"",
            address:"111 Walnut St",city:"Chicago",state:"IL", zipCode:"66666",
            homeTel_1:"847", homeTel_2:"123",homeTel_3:"4567",workTel_1:"",workTel_2:"",workTel_3:"",
            workTel_ext:"").save(flush:true)
    }

    private def createStudent(family) {
        //        def sId = Student.findBy + 1
        def aStudent = new Student(lastName:"wang",firstName:"Linda",chineseName:"", birthDay: new Date(),gender:"F")
        aStudent.save(flush:true)
        family.addToStudents(aStudent)
        family.save(flush:true)
    }

    private def createAdmin() {
        def adminRole = new org.xilin.Role(authority: "ROLE_ADMIN", description: "Administrator")
        adminRole.save(flush:true)
        def password = authenticateService.passwordEncoder("adminadmin")
        def admin = new org.xilin.User(username:"admin",passwd:password,enabled:true,emailShow:true,description:"Administrator",email:"xilin.it@gmail.com")
        admin.save(flush:true)
        adminRole.addToPeople(admin)
        return admin
    }

    private def createRequestmap() {
        new Requestmap(url:"/**",configAttribute:"IS_AUTHENTICATED_ANONYMOUSLY").save()
        new Requestmap(url:"/todo/**",configAttribute:"IS_AUTHENTICATED_FULLY").save()
        new Requestmap(url:"/user/list/**",configAttribute:"ROLE_ADMIN").save()
    }
    /*
    private def createUser() {
    def adminRole = new org.xilin.Role(authority: "ROLE_ADMIN", description: "A super user")
    adminRole.save()
    //  def admin = new org.xilin.User(username: "admin", userRealName: "xilin admin", passwd: "admin")
    //   admin.save()
    def password = authenticateService.passwordEncoder("admin5")
    def admin = new org.xilin.User(username:"admin",passwd:password,enabled:true,emailShow:true,description:"admin user",email:"xilin.it@gmail.com",fatherFirstName:"f",fatherLastName:"w",fatherChineseName:"",motherFirstName:"f",motherLastName:"w",motherChineseName:"",address:"236",city:"itasca",State:"IL",zipCode:"60143",homePhone:"",workPhone:"",referedBy:"")
    admin.save()
    adminRole.addToPeople(admin)

    def defaultRole = new org.xilin.Role(authority: "ROLE_USER", description: "student family")
    defaultRole.save()
    def passwd1 = authenticateService.passwordEncoder("student7")
    def student = new org.xilin.User(username:"student",passwd:passwd1,enabled:true,emailShow:true,description:"student",email:"xilin.it@gmail.com",fatherFirstName:"f",fatherLastName:"w",fatherChineseName:"",motherFirstName:"f",motherLastName:"w",motherChineseName:"",address:"236",city:"itasca",State:"IL",zipCode:"60143",homePhone:"",workPhone:"",referedBy:"")
    student.save()
    defaultRole.addToPeople(student)

    def staffRole = new org.xilin.Role(authority: "ROLE_STAFF", description: "teacher and staff")
    staffRole.save()
    def passwd2 = authenticateService.passwordEncoder("teacher7")
    def staff = new org.xilin.User(username:"teacher",passwd:passwd2,enabled:true,emailShow:true,description:"teacher",email:"xilin.it@gmail.com",fatherFirstName:"f",fatherLastName:"w",fatherChineseName:"",motherFirstName:"f",motherLastName:"w",motherChineseName:"",address:"236",city:"itasca",State:"IL",zipCode:"60143",homePhone:"",workPhone:"",referedBy:"")
    staff.save()
    staffRole.addToPeople(staff)
    }
     */
}
